package org.phalanx.gwt.client.screens;

import java.util.HashMap;

import com.google.gwt.user.client.ui.Panel;
import com.google.gwt.user.client.ui.RootPanel;


public class ContextPanelChooser {
	private HashMap<String,Panel> panelTable;
	private Panel contextPanel;
	private String currentContextPanelName;
	private String lastContextPanelName;
	private Panel parentPanel;

	public ContextPanelChooser(Panel parentPanel){
		panelTable = new HashMap<String, Panel>();
		this.setParentPanel(parentPanel);
	}

	public void setContextPanel(String contextName){
		if (panelTable.containsKey(contextName)){
			Panel loadedPanel = panelTable.get(contextName);

			setLastContextPanelName(currentContextPanelName);

			if (loadedPanel instanceof PhalanxContextEvent){
				PhalanxContextEvent p = (PhalanxContextEvent)loadedPanel;
				p.onContextVisible();
			}

			currentContextPanelName = contextName;

			contextPanel = panelTable.get(contextName);

			parentPanel.clear();
			parentPanel.add(contextPanel);
		}
	}

	public void addPanelToChooser(String contextName, Panel contextPanel){
		if (!panelTable.containsValue(contextPanel)){
			panelTable.put(contextName, contextPanel);
		}
	}

	public void removePanelFromChooser(String contextName){
		if (panelTable.containsKey(contextName)){
			Panel removedPanel = panelTable.get(contextName);

			if (removedPanel instanceof PhalanxContextEvent){
				((PhalanxContextEvent)removedPanel).onContextClosed();
			}

			panelTable.remove(contextName);
		}
	}

	public void clearChooserTable(){
		panelTable.clear();
	}

	public Panel getContextPanel(String contextName){
		return panelTable.get(contextName);
	}

	public Panel getContextPanel() {
		return contextPanel;
	}

	public void setParentPanel(Panel parentPanel) {
		this.parentPanel = parentPanel;
	}

	public Panel getParentPanel() {
		return parentPanel;
	}

	private void setLastContextPanelName(String lastContextPanelName) {
		this.lastContextPanelName = lastContextPanelName;
	}

	public String getLastContextPanelName() {
		return lastContextPanelName;
	}

}
